<script setup lang='ts'>
import { reactive, ref } from 'vue';
import { editMenuLReq, addMenuReq } from '../../../api/menu/menu';
import { ElMessage } from 'element-plus';

const dialogVisible = ref(false);
const dialogRef = ref();
const props = defineProps([
  "addIsEditSwitch",
]);

const emit = defineEmits<{
  (e: "editItemData"): void;
}>()

const rules ={
menuName:[ { required: true, message: '该内容为必填', trigger: 'blur' },],
level:[ { required: true, message: '该内容为必填', trigger: 'blur' },],
path:[ { required: true, message: '该内容为必填', trigger: 'blur' },],
parentName:[ { required: true, message: '该内容为必填', trigger: 'blur' },],

}

const data = reactive({
  menuName: "",
  level: "",
  path: "",
  parentName: "",
  isStatus: false
});

const handleOpen =  (row: any) => {
  dialogVisible.value = true;
  Object.assign(data,row)
}

const handleClose = ()=> {
  dialogVisible.value = false;
  handleIsAddOrEdit();
}

const save = async () => {
  await dialogRef.value.validate();

  let res;
  if( props.addIsEditSwitch ) {
    res = await addMenuReq(data);
  } else {
    res = await editMenuLReq(data);
    handleClose();
    emit("editItemData")
  }
  if(res.code == 200) return ElMessage.success((props.addIsEditSwitch?`新增`:`编辑`)+`成功!`);
}

// 判断是否为编辑或者新增
const handleIsAddOrEdit = () => {
  if( props.addIsEditSwitch ) {
    Object.assign(data,{
        menuName: "",
        level: "",
        path: "",
        parentName: "",
        isStatus: false
    })
  }
}

defineExpose({
  handleOpen
})
</script>

<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      :title="(props.addIsEditSwitch ? '新增' : '编辑')+'菜单'"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        :rules="rules"
        :model="data"
        ref="dialogRef"
      >
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="data.menuName" />
        </el-form-item>
        <el-form-item label="菜单类级" prop="level">
          <el-input v-model="data.level" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="path">
          <el-input v-model="data.path" />
        </el-form-item>
        <el-form-item label="菜单父级" prop="parentName">
          <el-input v-model="data.parentName" />
        </el-form-item>
        <el-form-item label="是否启动">
          <el-switch v-model="data.isStatus" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="save">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">

</style>